//
//  WinInfoController.swift
//  SlaughterClient
//
//  Created by 邱仙凯 on 2020/2/10.
//  Copyright © 2020 zwb. All rights reserved.
//

import UIKit
import WebKit
class ZyaWinInfoController: UIViewController {
    
    lazy var timeflagView:ZyaTimeFlagView = {
        let v = ZyaTimeFlagView()
        return v
    }()
    
    lazy var tbinfo_V: TbInfoNewView = {
        
        var v = TbInfoNewView()
        return v
        
        
    }()
 
    var titleInfoView: ZyaTitleInfoView!
    var winListView:ZyaWinListView!
    var headView = UIView()
    var helper = ZyaTenderHelper()
    var tbListCount = 1
    var oneItemH = 170
    var voccd = ""
    var vouid = ""

    lazy var zbInstructions:UILabel = {
        let lab :UILabel = UILabel()
        lab.font = UIFont.systemFont(ofSize: 15)
        lab.backgroundColor = .white
        lab.textAlignment = .center
        lab.text = "中标说明"
        return lab
    }()
    lazy var zbLine:UIView = {
        let view:UIView = UIView()
        view.backgroundColor = #colorLiteral(red: 0.7764705882, green: 0.7764705882, blue: 0.7843137255, alpha: 1)
        
        return view
    }()
    
    lazy var tableView: UITableView = {
        let tableView = UITableView()
        return tableView
    }()
    
    var contentWeb: WKWebView = {
        let web = WKWebView()
        web.backgroundColor = .darkGray
        return web
    }()
    
    var idkey:String = ""
    
    
    var innerType:ZTBInnerType?
    private var one = ZyaZtbContentModel(JSON:["":""])!
    var  enterType = ZyaEnterType.none  // 9 目前是客户网使用，9 审批流不会出来审批信息   9 就是客户网 none
    var todoType = ZyaTodoType.normal
    var processid = ""
    
    private let leading = 10
    private let trading = -10
    private var lastFileBtn:ZyaFileButton?
    private var zbFiles = [ZyaZbFile]()
    var listType = TBandJPType.TB
    
    init(listType:TBandJPType,idkey: String) {
        super.init(nibName: nil, bundle: nil)
        self.idkey = idkey
        self.listType = listType
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        self.title =  "我的成交"
        if self.enterType == .none {
            tableView.frame = self.view.bounds
        } else {
            tableView.frame = CGRect(x:0,y:0,width:KSGlobal.screenW,height: self.view.frame.height - self.ksTabbarHeight - self.ksStatusbarHeight)
        }
        
        if self.enterType == .audited && self.listType == .TB { // 出价的   审核  可以查看出价记录
            
            
            
            self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "出价记录", style: .done, target: self, action: #selector(tbRecordAction))
     
            
        }
        
        self.view.addSubview(tableView)
        headView.frame = CGRect(x:0,y:0,width:KSGlobal.screenW,height: 600)
        self.tableView.tableHeaderView = headView
        headView.addSubview(timeflagView)
        timeflagView.snp.makeConstraints { (make) in
            make.left.equalTo(self.view)
            make.right.equalTo(self.view)
            make.top.equalTo(headView)
            make.height.equalTo(40)
        }
        
       
        
        
        if enterType == .none {
            titleInfoView = (Bundle.main.loadNibNamed("ZyaTitleInfoView", owner: self, options: nil)?[0] as! ZyaTitleInfoView)
        }
        
       
        zbInstructions.text = self.listType == .TB ? "中标说明" : "成交说明"
     
        winListView = (Bundle.main.loadNibNamed("ZyaWinListView", owner: self, options: nil)?[0] as! ZyaWinListView)
        winListView.enterType = self.enterType
        
        if enterType == .none {
            headView.addSubview(titleInfoView)
        }
        headView.addSubview(tbinfo_V)
       
       
        headView.addSubview(winListView)
        winListView.titleLab.text = "成交信息"
        
        tbinfo_V.snp.makeConstraints { (make) in
            make.left.equalTo(self.view)
            make.right.equalTo(self.view)
            make.top.equalTo(titleInfoView.snp.bottom).offset(5)
            
         }
        let tapB = UITapGestureRecognizer()
        tapB.numberOfTapsRequired = 1
        tapB.addTap { [unowned self] ges in
            
            zyago2TenderInfoVC(listType: self.listType, fromVC:self,idkey:self.one.zZbId.unwrap, innerType: .chujiaRecordKHW)
            
            
            
        }
        self.tbinfo_V.contContentLabel.addGestureRecognizer(tapB)
     
        
        if enterType == .none {
            titleInfoView.snp.makeConstraints { (make) in
                make.left.equalTo(self.view).offset(leading)
                make.right.equalTo(self.view).offset(trading)
                make.top.equalTo(timeflagView.snp.bottom).offset(5)
            }
        }
        
        
   
        
        self.winListView.snp.makeConstraints { (make) in
            make.left.equalTo(tbinfo_V)
            make.right.equalTo(tbinfo_V)
            make.top.equalTo(self.tbinfo_V.snp.bottom)
            
        }
        
        
        if enterType == .none {
            headView.addSubview(zbLine)
            zbLine.snp.makeConstraints { (make) in
                make.left.equalTo(self.view).offset(leading)
                make.right.equalTo(self.view).offset(trading)
                make.top.equalTo(self.winListView.snp.bottom).offset(20)
                make.height.equalTo(1)
            }
            headView.addSubview(zbInstructions)
            zbInstructions.snp.makeConstraints { (make) in
                make.centerX.equalTo(self.view)
                make.width.equalTo(80)
                make.top.equalTo(self.winListView.snp.bottom).offset(5)
                make.height.equalTo(30)
            }
            headView.addSubview(contentWeb)
            contentWeb.navigationDelegate = self
            contentWeb.snp.makeConstraints { (make) in
                make.left.equalTo(self.view).offset(leading)
                make.right.equalTo(self.view).offset(trading)
                make.height.equalTo(30)
                make.top.equalTo(self.zbInstructions.snp.bottom).offset(5)
            }
            
            tableView.tableFooterView = UIView()
        }
        
        var api:API?
        if self.listType == .TB {
            api = API.queryMytenderWinInfo(id_key: idkey)
        } else {
            api = API.queryAuctionInfo(id_key: idkey)
        }
        
        
        KSNetwork.shared.doRequest(api!) { (data:BaseResult<ZyaZtbContentModel>) in
            if data.flag == TRUE {
                if let info = data.infoObjCombine {
                    self.one = info
                    
                    
                    let paraph = NSMutableParagraphStyle()
                    //将行间距设置为28
                    paraph.lineSpacing = 9
                    //样式属性集合
                    let attributes = [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 17),
                                      NSAttributedString.Key.paragraphStyle: paraph]
                    
                    if self.enterType == .none {
                        // 空格为了UI效果
                        self.titleInfoView.titleLab.text = info.zTitle.unwrap
                        
                  
                        self.titleInfoView.addr.text = "\(info.zCity.unwrap)  成交时间：\(info.zCreateTm.unwrap)"
                        
                        self.timeflagView.setTimeFlagInfo(status: "已成交", countDown: "\(info.zEndDate.unwrap)结束",model: self.one)
                    }
                    if self.listType == .TB {
                        
                        var arrx = info.zbInfoAll.unwrap.components(separatedBy: "#")
                        if let inx = arrx.getIndexFor({ onex in
                            return onex.contains("招标编号")
                        }) {
                            arrx.remove(at: inx)
                        }
                        let joinsss = arrx.joined(separator: "#")
 
                        self.tbinfo_V.content1.multiLineTitleContentShow(contentStr: joinsss, fontx: 16)
                        
                        self.tbinfo_V.contentLinkStr = "招标编号:\(info.zRecordNo.unwrap)"
                        self.tbinfo_V.ks_height = self.tbinfo_V.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
                        
                        
                    } else {
                        let ddddd = "报价单位:\(info.zOrgNm.unwrap)#商品名称:\(info.zGoodsNm.unwrap)#猪只类型:\(info.zPigType.unwrap)#数量:\(info.zNum.unwrap)#均重:\(info.zAvgWeight.unwrap)#出栏时间:\(info.zDate.unwrap)至\(info.zDateEnd.unwrap)#报价时间:起始\(info.zBeginDate.unwrap)#-:截止\(info.zEndDate.unwrap)#联系人:\(info.zName.unwrap)"
                        
 
                        
                        self.tbinfo_V.content1.multiLineTitleContentShow(contentStr: ddddd, fontx: 16)
                        
                        self.tbinfo_V.contentLinkStr = "报价编号:\(info.zZbNo.unwrap)"
                        self.tbinfo_V.ks_height = self.tbinfo_V.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
                        
 
                    }
                    
                    if self.listType == .TB {
                        self.winListView.unitNm = info.zUnitNm
                        self.winListView.tbList = info.tbInfo
                        self.tbListCount = info.tbInfo.isSome ? info.tbInfo!.count : 1
                    } else {
                        self.winListView.unitNm = info.zUnitNm
                        self.winListView.tbList = info.bidInfo
                        self.tbListCount = info.bidInfo.isSome ? info.bidInfo!.count : 1
                    }
                    if let itemss = info.tbInfo?.first?.tbInfoNew {
                        let jH = itemss.components(separatedBy: "#").count
                        let gH = itemss.components(separatedBy: "\n").count
                        let hhhh = (jH + gH) * 28
                        self.oneItemH = hhhh
                        print(hhhh)
                    }
                    self.headView.ks_height = CGFloat(220) +  CGFloat(self.tbListCount * self.oneItemH)
              
                    
                    if self.enterType == .none {
                        
                        self.contentWeb.loadHTMLString(adaptHtml(info.zContent.unwrap), baseURL: nil)
                    } else {
              
                        if let files = info.zbFile {
                            self.zbFiles = files
                            for i in 0..<files.count {
                                let btn = ZyaFileButton()
                                btn.tag = i
                                btn.setTitle(files[i].zName, for: .normal)
                                btn.addTarget(self, action: #selector(self.btnAction(sender:)), for: .touchUpInside)
                                self.headView.addSubview(btn)
                                btn.snp.makeConstraints { (make) in
                                    if self.lastFileBtn.isSome {
                                        make.top.equalTo(self.lastFileBtn!.snp.bottom).offset(6)
                                    } else {
                                        make.top.equalTo(self.winListView.snp.bottom).offset(6)
                                    }
                                    make.width.equalTo(KSGlobal.screenW)
                                    make.height.equalTo(30)
                                    make.centerX.equalTo(self.headView)
                                }
                                self.lastFileBtn = btn
                            }
                        }
                        
                    }
                    self.tableView.reloadData()
                    
                    
                    
                }
                
                
            } else {
                
            }
        }
        
    }
    
    @objc func tbRecordAction() {
        if one.zDtradeType == "5" && listType == .TB { // 药品出价
            self.helper.go2TenderRecord(controller:self,id:one.zZbId.unwrap)
         } else {
            let  vc = ZyaTenderListVC(titleStr: .tbRecordKHW, z_zb_id: one.zZbId.unwrap)
            self.navigationController?.pushViewController(vc, animated: true)
        }
         
     }
    
    @objc func btnAction(sender:UIButton) {
        let file = self.zbFiles[sender.tag]
        let cwebV = CommonWebController()
        let str1 = "\(file.zPicUrl.unwrap)"
        cwebV.reportUrl = str1
        cwebV.title = file.zPicUrl.unwrap
        self.navigationController?.pushViewController(cwebV, animated: true)
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        
        
        
    }
    
    
}

extension ZyaWinInfoController: WKNavigationDelegate {
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        var webheight = 0.0
        
        
        self.contentWeb.evaluateJavaScript("document.documentElement.clientHeight") { [unowned self] (result, error) in
            
            if let tempHeight: Double = result as? Double {
                webheight = tempHeight
            }
            DispatchQueue.main.async { [unowned self] in
                
                let endRect = zyadealwithHeight(height: webheight, rect: self.contentWeb.frame)
                self.contentWeb.snp.remakeConstraints { (make) in
                    
                    make.left.equalTo(self.view).offset(self.leading)
                    make.right.equalTo(self.view).offset(self.trading)
                    make.height.equalTo(webheight)
                    make.top.equalTo(self.zbInstructions.snp.bottom).offset(5)
                }
                if let itemss = self.one.tbInfo?.first?.tbInfoNew {
                    let jH = itemss.components(separatedBy: "#").count
                    let gH = itemss.components(separatedBy: "\n").count
                    let hhhh = (jH + gH) * 28
                    self.oneItemH = hhhh
                    print(hhhh)
                }
                self.headView.ks_height = CGFloat(webheight + 150 + 200) +  CGFloat(self.tbListCount * self.oneItemH)
                self.tableView.reloadData()
            }
        }
        
    }
}


func zyadealwithHeight(height:Double,rect:CGRect) -> CGRect {
    var tempFrame = rect
    var webheight = height
    
    if webheight < 600 {
        webheight = 600
    }
    if webheight < 1000 {
        tempFrame.size.height = CGFloat(webheight)
    } else if webheight > 1000 &&  webheight < 2000 {
        tempFrame.size.height = CGFloat(webheight) * 0.75
    } else  if webheight > 2000 && webheight < 3000 {
        tempFrame.size.height = CGFloat(webheight) * 0.65
    } else  if webheight > 3000 && webheight < 5000 {
        tempFrame.size.height = CGFloat(webheight) * 0.55
    } else if webheight > 5000 && webheight > 7000 {
        tempFrame.size.height = CGFloat(webheight) * 0.45
    } else if webheight > 7000 && webheight > 9000 {
        tempFrame.size.height = CGFloat(webheight) * 0.35
    }
    return tempFrame
}


class ZyaFileButton:UIButton {
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setTitleColor(.darkGray, for: .normal)
        self.titleLabel?.font = UIFont.systemFont(ofSize: 13)
    }
    override func setTitle(_ title: String?, for state: UIControl.State) {
        super.setTitle(title, for: state)
        if title.unwrap.contains("doc") {
            self.setImage(UIImage(named: "file_w"), for: .normal)
        } else if title.unwrap.contains("xls") {
            self.setImage(UIImage(named: "file_x"), for: .normal)
        } else if title.unwrap.contains("pdf") {
            self.setImage(UIImage(named: "file_p"), for: .normal)
        } else {
            self.setImage(UIImage(named: "file_default"), for: .normal)
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        let width_r = 25
        // 设置imageView
        imageView?.frame = CGRect(x: 10 , y: 0, width: width_r, height: width_r)
        // 设置title
        titleLabel?.frame = CGRect(x: 40 , y: 0, width: Int(KSGlobal.screenW - 40), height: width_r)
        
        
    }
    
}
